//
//  HJPersonalAvatarController.m
//  KaiChat
//
//  Created by lx on 2023/12/19.
//

#import "HJPersonalAvatarController.h"
#import "HJCenterTitleCell.h"
#import <Photos/Photos.h>
#import "TOCropViewController.h"
#import "HJMinePresent.h"

@interface HJPersonalAvatarController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDataSource, UITableViewDelegate, TOCropViewControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, weak) UIImageView *imageView;

@end

@implementation HJPersonalAvatarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.alpha = 0;
    self.navigationBar.title = @"Photo";
    self.navigationBar.backgroundColor = UIColor.blackColor;
    self.navigationBar.titleTextColor = UIColor.whiteColor;
    [self.navigationBar.backBarButton whiteColor];
    self.view.backgroundColor = UIColor.blackColor;
    
    UIImageView *imageView = [UIImageView addToView:self.view];
    imageView.backgroundColor = UIColor.blackColor;
    imageView.image = _image;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [imageView tj_setImageWithUrl:HJUserInfo.avatar];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.bottom.offset(0);
    }];
    
    CGFloat contentViewH = 2 * 50 + TabbarSafeBottomMargin;
    UIView *bottomView = [UIView addToView:self.view];
    bottomView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, contentViewH);
    [bottomView addRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:20];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(0);
        make.height.offset(contentViewH);
    }];
    
    [self.tableView removeFromSuperview];
    [bottomView addSubview:self.tableView];
    [self.tableView registerClass:HJCenterTitleCell.class forCellReuseIdentifier:@"HJCenterTitleCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 50;
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(0);
        make.bottom.offset(0);
    }];
    
    _imageView = imageView;
    
}

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        tableView.separatorColor = [UIColor tj_separatorColor];
        tableView.backgroundColor = [UIColor tj_backgroundColor];
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.showsHorizontalScrollIndicator = NO;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedRowHeight = 0;
        
        if (@available(iOS 15.0, *)) {
            tableView.sectionHeaderTopPadding = 0;
        }
        
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCenterTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJCenterTitleCell" forIndexPath:indexPath];
    HJCellModel *model = self.datas[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJCellModel *model = self.datas[indexPath.row];
    if ([model.identifier isEqualToString:@"Save"]) {
        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        return;
    }
    
    if ([model.identifier isEqualToString:@"Photo"]) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
            [self alertWithTitle:nil message:@"Gallery permission is not enabled Go to settings to turn on gallery permissions" leftButtonName:@"Cancel" rightButtonName:@"OK" leftButtonBlock:^{
            } rightButtonBlock:^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            }];
            return;
        }
        [self chooseFromPhotoAlbum];
        return;
    }
    
}

- (void)chooseFromPhotoAlbum {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];
    
    
    TOCropViewController *cropViewController = [[TOCropViewController alloc] initWithImage:image];
    cropViewController.delegate = self;
    cropViewController.doneButtonColor = UIColor.whiteColor;
    cropViewController.cancelButtonColor = UIColor.whiteColor;
    cropViewController.doneButtonTitle = @"Done";
    cropViewController.cancelButtonTitle = @"Cancel";
    cropViewController.rotateClockwiseButtonHidden = YES;
    cropViewController.aspectRatioPickerButtonHidden = YES;
    cropViewController.resetButtonHidden = YES;
    cropViewController.aspectRatioPickerButtonHidden = YES;
    cropViewController.rotateClockwiseButtonHidden = YES;
    cropViewController.rotateButtonsHidden = YES;
    cropViewController.aspectRatioLockEnabled = YES;
    cropViewController.minimumAspectRatio = 1.0;
    cropViewController.aspectRatioPreset = TOCropViewControllerAspectRatioPresetSquare;
    [picker presentViewController:cropViewController animated:YES completion:nil];
    
}

- (void)cropViewController:(nonnull TOCropViewController *)cropViewController
            didCropToImage:(nonnull UIImage *)image withRect:(CGRect)cropRect
                     angle:(NSInteger)angle {
    TJWeakify(self)
    [cropViewController dismissToRootViewController:YES completion:^{
        [weakself uploadImageWithImage:image];
    }];
    
}
 
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if(error) {
        [HJHUD showErrorMessage:@"Save failed,please check permissions"];
    } else {
        [HJHUD showSucceedMessage:@"Saved successfully"];
    }
}


- (void)uploadImageWithImage:(UIImage *)image {
    
    [HJHUD showLoadingInView:self.view text:nil];
    
    [image asynImageSize:CGSizeMake(120, 120) color:UIColor.whiteColor finishiBlock:^(UIImage *drawImage) {
        
        NSString *objectKey = getUploadFileKey(HJFileTypeImage, [NSString stringWithFormat:@"%@.%@", [NSString stringWithFormat:@"%.f", NSDate.date.timeIntervalSince1970 * 1000].md5, @"jpeg"]);
        
        [HJNetworking.shareNetwork uploadImageWithObejctKey:objectKey fileData:UIImageJPEGRepresentation(drawImage, 0.7) progress:nil success:^(NSString * _Nonnull url) {
            NSString *imageUrl = url;
            
            [HJMinePresent modifyAvatar:imageUrl complete:^(NSError * _Nullable error) {
                [HJHUD hiddenLoading];
                if (!error) {
                    [HJHUD showSucceedMessageTip];
                    HJUserInfo.avatar = imageUrl;
                    NSString *key = [SDWebImageManager.sharedManager cacheKeyForURL:imageUrl.URL];
                    [SDImageCache.sharedImageCache storeImage:drawImage forKey:key toDisk:YES completion:^{
                        dispatch_async_main_queue(^{
                            self.imageView.image = drawImage;
                            if (self.complete) {
                                self.complete(imageUrl);
                            }
                            [[NSNotificationCenter defaultCenter] postNotificationName:modifyAvatarSucceedNotification object:image];
                        });
                    }];
                } else {
                    [HJHUD showErrorMessageTip];
                }
            }];
        } failure:^(NSError * _Nonnull error) {
            [HJHUD showErrorMessageTip];
        }];
    }];
    
}


- (NSArray *)datas {
    if (!_datas) {
        _datas = @[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.text = @"Photo";
                model.identifier = @"Photo";
                model.textFont = UIFontMake(16);
                model.textColor = UIColor.tj_333333Color;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.text = @"Save Photo";
                model.identifier = @"Save";
                model.textFont = UIFontMake(16);
                model.textColor = UIColor.tj_333333Color;
            }],
        ];
    }
    return _datas;
}

@end
